package com.iotimc.attendancesystem.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.daimajia.numberprogressbar.NumberProgressBar;
import com.iotimc.attendancesystem.R;
import com.iotimc.attendancesystem.datautil.ImageData;
import com.pefis.natives.Ast2600JNI;
import com.pefis.natives.PfsBioInfo;
import com.pefis.view.FaceDetectionView;

import java.util.Timer;
import java.util.TimerTask;

public class AddHeadActivity extends BaseActivity implements Runnable {
    private static final String TAG = "AddHeadActivity";
    private boolean mLoop = false;

    byte[] mColorImageFrame;
    byte[] mProcessImageFrame;
    byte[] m_Template;
    int mImageWidth;
    int mImageHeight;
    Rect mRect;

    private ImageView mPreview;
    private ViewfinderView vfv;
    private RatingBar ratingBar;
    private CheckBox mSwitchCamera;
    private TextView mAddHint;
    private NumberProgressBar numberProgressBar;
    Intent mIntent;

    private Thread previewThread;

    private boolean mColorCamera = true;

    private MediaPlayer mPlay;
    private FaceDetectionView mFaceDetectionView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addhead);
        mPlay = MediaPlayer.create(this, R.raw.tip);
        mFaceDetectionView = findViewById(R.id.faceDetectionView);
        numberProgressBar = findViewById(R.id.number_progress_bar);
        mPreview = findViewById(R.id.preview);
        vfv = findViewById(R.id.vfv);
        ratingBar =  findViewById(R.id.ratingBar);
        mSwitchCamera =  findViewById(R.id.switchCamera);
        mAddHint =  findViewById(R.id.addHint);
        findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setResult(0x81, mIntent);
                AddHeadActivity.this.finish();
            }
        });
        ratingBar.setNumStars(PfsBioInfo.getInstance().enroll_face_count[0]);
        ratingBar.setMax(PfsBioInfo.getInstance().enroll_face_count[0]);

        mSwitchCamera.setOnCheckedChangeListener(mCheckedChangeListener);

        mImageWidth = PfsBioInfo.getInstance().face_img_w[0];
        mImageHeight = PfsBioInfo.getInstance().face_img_h[0];
        mColorImageFrame = new byte[mImageWidth * mImageHeight];
        mProcessImageFrame = new byte[mImageWidth * mImageHeight];
        m_Template = new byte[PfsBioInfo.getInstance().enroll_template_size[0]];

        previewThread = new Thread(this);
        mLoop = true;
        previewThread.start();
        mIntent = new Intent();
        mAddHint.setText(R.string.leftFace);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    }

    private OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                                     boolean isChecked) {

            mColorCamera = !mColorCamera;
            // Log.e("","value = "+mCheckedDay);
        }
    };

    Handler mImageDraw = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x80:

                    mPreview.setImageBitmap((Bitmap) msg.obj);
                    break;

                case 0x81:


                    break;

                case 0x82:

                    Log.i(TAG, "handleMessage: "+0x80);
                    ImageData.setData(PfsBioInfo.getInstance().m_bmp,
                            mProcessImageFrame, m_Template, mImageWidth,
                            mImageHeight, mRect);

                    setResult(0x80, mIntent);
                    AddHeadActivity.this.finish();
                    break;

                case 0x83:
                    // ImageData.setData(PfsBioInfo.getInstance().m_bmp,
                    // mProcessImageFrame, m_Template, mImageWidth, mImageHeight,
                    // mRect);
                    setResult(0x81, mIntent);

                    break;

                case 0x84:
                    mAddHint.setText(msg.arg1);
                    break;
                default:
                    Log.i(TAG, "handleMessage: "+msg.what);
                    ratingBar.setProgress(msg.what);
                    numberProgressBar.setProgress(msg.what);
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        mLoop = false;
        super.onDestroy();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        if (mPlay.isPlaying()) {
            mPlay.stop();
        }
        mPlay.release();
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        int vnRet;
        int enroll_seq = 0;
        int[] dup_id = new int[1];
        int contextId = PfsBioInfo.getInstance().mContextID;
        int ret = Ast2600JNI.getInstance().pisFcInfraredLedControl(
                PfsBioInfo.getInstance().mContextID,
                PfsBioInfo.PFSBIO_IR_LED_HIGH_ON);
        short[] faceRect = new short[4];
        Rect rect = null;
        int index = 0;

        while (mLoop) {
            // 人脸抓拍成功后语音开始提示
            if (!mPlay.isPlaying()) {
                mPlay.start();
            }
            Ast2600JNI.getInstance().pisFcColorImageCapture(
                    PfsBioInfo.getInstance().mContextID, mColorImageFrame);
            Ast2600JNI.getInstance().pisFcGrayImageCapture(
                    PfsBioInfo.getInstance().mContextID, mProcessImageFrame);

            if (index % PfsBioInfo.getInstance().enroll_face_count[0] == 0) {
                if (index / PfsBioInfo.getInstance().enroll_face_count[0] == 0
                        || index
                        / PfsBioInfo.getInstance().enroll_face_count[0] == 6) {
                    Message message = mImageDraw.obtainMessage(0x84,
                            R.string.zeroFace, 0, null);
                    message.sendToTarget();
                } else if (index
                        / PfsBioInfo.getInstance().enroll_face_count[0] == 2) {
                    Message message = mImageDraw.obtainMessage(0x84,
                            R.string.leftFace, 0, null);
                    message.sendToTarget();
                } else if (index
                        / PfsBioInfo.getInstance().enroll_face_count[0] == 3) {
                    Message message = mImageDraw.obtainMessage(0x84,
                            R.string.rightFace, 0, null);
                    message.sendToTarget();
                } else if (index
                        / PfsBioInfo.getInstance().enroll_face_count[0] == 4) {
                    Message message = mImageDraw.obtainMessage(0x84,
                            R.string.upFace, 0, null);
                    message.sendToTarget();
                } else if (index
                        / PfsBioInfo.getInstance().enroll_face_count[0] == 5) {
                    Message message = mImageDraw.obtainMessage(0x84,
                            R.string.downFace, 0, null);
                    message.sendToTarget();
                }
            }

            if (mColorCamera) {
                PfsBioInfo.getInstance().CreateColorBitmapFromBayer(
                        mColorImageFrame);
            } else {
                PfsBioInfo.getInstance().CreateGrayBitmapFromBayer(
                        mProcessImageFrame);
            }

            Message message = mImageDraw.obtainMessage(0x80, 0, 0,
                    PfsBioInfo.getInstance().m_bmp);
            message.sendToTarget();

            vnRet = Ast2600JNI.getInstance().pisFcCheck(
                    PfsBioInfo.getInstance().mContextID, mProcessImageFrame,
                    mImageWidth, mImageHeight, faceRect);

            if (vnRet != PfsBioInfo.PFSBIO_OK) {

                Ast2600JNI.getInstance().pisLedControl(
                        PfsBioInfo.getInstance().mContextID,
                        PfsBioInfo.PFSBIO_OKNOLED, PfsBioInfo.PFSBIO_LED_OFF);
                message = mImageDraw.obtainMessage(0x81, 0, 0, null);
                message.sendToTarget();

                mFaceDetectionView.setRect(-10, -10, -10, -10);
                mFaceDetectionView.postInvalidate();
                continue;
            }

            double left = faceRect[0]*1.35,top = faceRect[2]*1.1;

            mFaceDetectionView.setRect((int) left, (int) top, faceRect[1]
                    - faceRect[0], faceRect[3] - faceRect[2]);
            mFaceDetectionView.postInvalidate();

            index++;

            rect = new Rect(faceRect[0], faceRect[2], faceRect[1], faceRect[3]);
            message = mImageDraw.obtainMessage(0x81, 0, 0, rect);
            message.sendToTarget();

            if ((index % PfsBioInfo.getInstance().enroll_face_count[0]) == 0) {
                vnRet = Ast2600JNI.getInstance().pisFcEnroll(
                        PfsBioInfo.getInstance().mContextID, enroll_seq,
                        mProcessImageFrame, mImageWidth, mImageHeight,
                        m_Template);

                if (vnRet != PfsBioInfo.PFSBIO_OK) {
                    index--;
                    continue;
                }

                enroll_seq++;

                mImageDraw.sendEmptyMessage(enroll_seq);

                if (enroll_seq >= PfsBioInfo.getInstance().enroll_face_count[0]) {
                    break;
                }
            } else {
                continue;
            }

        }

        mRect = rect;

        if (enroll_seq >= PfsBioInfo.getInstance().enroll_face_count[0]) {
            mImageDraw.sendEmptyMessage(0x82);
        } else {
            mImageDraw.sendEmptyMessage(0x83);
        }
    }
}
